package com.bluetooth.demo.ui;

import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bluetooth.demo.R;
import com.bluetooth.demo.event.HeartEvent;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

public class HeartFragment extends Fragment {

    private View mCurrentView;
    private LineChart mChart;
    private TextView tv_current;
    private TextView tv_high;
    private TextView tv_low;
    private TextView tv_average;
    private int high;
    private int low = -1;
    private long total;
    private long count;

    public HeartFragment() {
        // Required empty public constructor
    }

    public static HeartFragment newInstance() {
        HeartFragment fragment = new HeartFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mCurrentView = inflater.inflate(R.layout.fragment_heart, container, false);
        initChart();
        EventBus.getDefault().register(this);
        initView(mCurrentView);
        return mCurrentView;
    }

    private void initView(View mCurrentView) {
        tv_current = (TextView) mCurrentView.findViewById(R.id.tv_current);
        tv_high = (TextView) mCurrentView.findViewById(R.id.tv_high);
        tv_low = (TextView) mCurrentView.findViewById(R.id.tv_low);
        tv_average = (TextView) mCurrentView.findViewById(R.id.tv_average);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private void initChart() {
        //图表初始化
        mChart = (LineChart) mCurrentView.findViewById(R.id.chart1);

        // enable description text
        mChart.getDescription().setEnabled(false);
        // enable touch gestures
        mChart.setTouchEnabled(true);
        mChart.setPinchZoom(false);
        mChart.setScaleXEnabled(false);
        mChart.setScaleYEnabled(false);

        // get the legend (only possible after setting data)
        Legend l = mChart.getLegend();
        l.setEnabled(false);

        XAxis xl = mChart.getXAxis();
        xl.setAvoidFirstLastClipping(true);
        xl.setDrawGridLines(true);
        xl.setLabelCount(51, true);
        xl.setTextColor(Color.parseColor("#a7a5a6"));
        xl.setGridColor(Color.parseColor("#a7a5a6"));
        xl.setPosition(XAxis.XAxisPosition.BOTTOM);
        xl.setValueFormatter(new IAxisValueFormatter() {


            @Override
            public String getFormattedValue(float value, AxisBase axis) {

//                if (value < 20) {
//                    return String.valueOf(((int) value) * 3) + "s";
//                } else if (value < 1200) {
//                    return df.format(((int) value) * 3 / 60f) + "m";
//                } else {
//                    return "1h";
//                }

                return "";


            }
        });

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setLabelCount(21, true);
        leftAxis.setDrawGridLines(true);
        leftAxis.setTextColor(Color.parseColor("#a7a5a6"));
        leftAxis.setGridColor(Color.parseColor("#a7a5a6"));
        leftAxis.setAxisMinimum(0);
        leftAxis.setAxisMaximum(200);

        mChart.getAxisRight().setEnabled(false);


        ArrayList<Entry> tmpData = new ArrayList<Entry>();
        //设置一个临时数据
        for (int i = 0; i < 51; i++) {
            tmpData.add(new Entry(i, mChart.getAxisLeft().getMinWidth()));
        }

        LineDataSet tmpSet = new LineDataSet(tmpData, "");
        tmpSet.setAxisDependency(YAxis.AxisDependency.LEFT);
        tmpSet.setLineWidth(0f);
        tmpSet.setColor(Color.parseColor("#a7a5a6"));
        tmpSet.setDrawCircles(false);
        tmpSet.setDrawValues(false);
        tmpSet.setDrawCircleHole(false);
        tmpSet.setHighLightColor(Color.TRANSPARENT);
        LineData tmpLine = new LineData(tmpSet);
        // set data
        mChart.setData(tmpLine);
        mChart.notifyDataSetChanged();
        mChart.invalidate();
    }

    //更新绘制图表
    private void updateChart(float value) {
        LineData data = mChart.getData();
        if (data != null) {
            if (data.getDataSetCount() == 1) {
                ArrayList<Entry> yVals1 = new ArrayList<Entry>();
                yVals1.add(new Entry(0, value));
                LineDataSet set1 = new LineDataSet(yVals1, "");
                set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                set1.setColor(Color.parseColor("#f64a4b"));
                set1.setDrawCircles(false);
                set1.setDrawValues(false);
                set1.setHighLightColor(Color.parseColor("#2ecc71"));
                set1.setDrawCircleHole(false);
                set1.setHighlightEnabled(false);
                data.addDataSet(set1);
                data.notifyDataChanged();
                mChart.notifyDataSetChanged();
                mChart.invalidate();
            } else {
                ILineDataSet set1 = data.getDataSetByIndex(1);
                data.addEntry(new Entry(set1.getEntryCount(), value), 1);
                data.notifyDataChanged();
                mChart.notifyDataSetChanged();
                mChart.invalidate();

            }
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(HeartEvent event) {
        int current = event.getHeartrate();
        updateChart(current);
        if (current > high) {
            high = current;
        }
        if (low == -1 || current < low) {
            low = current;
        }
        if(current>0){
            total += current;
            count++;
        }
        tv_current.setText("当前心率:" + current);
        tv_high.setText("最高心率:" + high);
        tv_low.setText("最低心率:" + low);
        tv_average.setText("平均心率:" + (total / count));
    }

}
